<template>
  <div v-if="currentDevice.devices && currentDevice.devices.length > 0">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <b class="header-title">喷头控制</b>
        <el-button-group style="float:right;">
          <el-button type="primary" icon="el-icon-refresh" size="mini" @click="restart">重启设备</el-button>
          <el-button type="primary" icon="el-icon-s-operation" size="mini" :disabled="childSelected.length === 0" @click="showControlAll">控制选中</el-button>
        </el-button-group>
      </div>
      <el-collapse v-model="activeNames">
        <el-collapse-item v-for="(item,index) in currentDevice.steps" :key="index" :name="index">
          <template slot="title">
            <div class="collapse-title flex">
              <b style="min-width:48px;margin-right:12px;">{{ item.name }}</b>
              <el-badge
                v-for="(citem,cindex) in item.devices"
                :key="cindex"
                is-dot
                class="item"
                style="margin:0 1px;"
                :type="getValveClass(citem.spray_serialno)"
              />
              <div class="mlauto pr12">
                <span v-if="getSelectedValves(item) > 0" class="mr12">已选中：<b>{{ getSelectedValves(item) }}</b></span>
                <el-button-group>
                  <el-button type="primary" plain icon="el-icon-check" size="mini" @click.stop="selectAll(item)">全选</el-button>
                  <el-button type="default" plain icon="el-icon-close" size="mini" @click.stop="cancelAll(item)">反选</el-button>
                  <el-button type="success" plain icon="el-icon-refresh" size="mini" @click.stop="refresh(item)">刷新状态</el-button>
                </el-button-group>
              </div></div>
          </template>
          <div class="childs-container">
            <dl v-for="(citem,cindex) in item.devices" :key="cindex" class="menux" @click="showControl(citem)">
              <dt><img :src="getDeviceImage(citem)" alt=""></dt>
              <dd>{{ citem.name }}</dd>
              <dd>{{ getPwmInfos(citem.spray_serialno) }}</dd>
              <dd v-if="childSelected.includes(citem)" class="iconfont icon-active" />
            </dl>
          </div>
        </el-collapse-item>
      </el-collapse>
      <el-dialog
        v-el-drag-dialog
        title="喷头控制"
        :append-to-body="true"
        destroy-on-close
        :visible.sync="dialogVisible"
        width="600px"
      >
        <div class="tags">
          <el-tag
            v-for="(item,index) in childSelected"
            :key="index"
            closable
            type="primary"
            style="margin:8px 8px 8px 0;"
            @close="closeTag(index)"
          >
            {{ item.name }}
          </el-tag>
        </div>
        <div class="h20" />
        <el-form ref="form" :rules="rules" :model="formData" label-suffix="：" label-width="100px">
          <el-form-item label="启闭设定" prop="cycle">
            <el-radio-group v-model="actionType" @change="changeActionType">
              <el-radio :label="1">打开</el-radio>
              <el-radio :label="0">关闭</el-radio>
              <el-radio :label="2">占空比</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-row>
            <el-col :span="12"><el-form-item label="脉冲周期" prop="cycle">
              <el-input v-model="formData.cycle" placeholder="脉冲周期">
                <template slot="append">秒</template>
              </el-input>
            </el-form-item></el-col>
            <el-col :span="12"><el-form-item label="占空比" prop="PWM">
              <el-input v-model="formData.PWM" placeholder="占空比">
                <template slot="append">%</template>
              </el-input>
            </el-form-item></el-col>
          </el-row>
          <el-form-item>
            <el-button type="primary" icon="el-icon-check" @click="pwmValve('form')">提交</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { sendPWM, sendCommand, restartGw } from '@/api/device'
import { selectable } from '@/utils/selectable'
import { uniqueArr, convertArr2Obj } from '@/utils'
import { getDeviceImage, getDeviceStatus, getPwmInfo } from '@/utils/device'
export default {
  data() {
    return {
      activeName: 'first',
      activeNames: ['1'],
      actionType: 2,
      formData: {
        cycle: 60,
        PWM: 60,
        type: 'valves',
        valves: []
      },
      dialogVisible: false,
      childSelected: [],
      rules: {
        cycle: [
          { required: true, message: '请输入脉冲周期', trigger: 'blur' }
        ],
        PWM: [
          { required: true, message: '请输入占空比', trigger: 'blur' }
        ]
      },
      devicesObj: {}
    }
  },
  computed: {
    ...mapGetters(['currentDevice', 'devices'])
  },
  watch: {
    currentDevice: {
      handler(newVal) {
        this.$nextTick(() => {
          selectable('childs-container', 'menux', (list, dom) => {
            list.forEach((item, index) => {
              this.childSelected.push(newVal.steps[dom].devices[item])
            })
            this.childSelected = uniqueArr(this.childSelected)
          })
        })
      },
      deep: true,
      immediate: true
    },
    devices: {
      handler(newVal) {
        this.devicesObj = convertArr2Obj(newVal, 'serialno')
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    restart() {
      this.$confirm('确定要进行此操作吗？', '操作确认', { type: 'warning' }).then(() => {
        this.restartGw()
      })
    },
    async restartGw() {
      const { msg } = await restartGw(this.currentDevice.serialno)
      this.$message.success(msg)
    },
    changeActionType(val) {
      const map = {
        1: 100,
        0: 0,
        2: 60
      }
      this.formData.cycle = 60
      this.formData.PWM = map[val]
    },
    showControl(item) {
      if (!this.childSelected.includes(item)) {
        this.childSelected.push(item)
      } else {
        this.childSelected.splice(this.childSelected.findIndex((val) => {
          return val === item
        }), 1)
      }
      this.childSelected = uniqueArr(this.childSelected)
    },
    showControlAll() {
      this.dialogVisible = true
    },
    closeTag(index) {
      this.childSelected.splice(index, 1)
    },
    pwmValve(formName) {
      this.formData.valves = []
      this.$refs[formName].validate((valid) => {
        if (valid) {
          for (const nozzle of this.childSelected) {
            this.formData.valves.push(nozzle)
          }
          this.$confirm('确定要进行此操作吗？', '操作确认', { type: 'warning' }).then(() => {
            sendPWM(this.formData).then(res => {
              this.$message({ message: res.msg, type: 'success', showClose: true })
            })
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    refresh(cell) {
      const actions = [
        { namekey: 'READ_ALL_AIS', params: true },
        { namekey: 'READ_ALL_HOLDS', params: true }
      ]

      this.$confirm('确定要进行此操作吗？', '操作确认', { type: 'warning' }).then(() => {
        const rtu_devices = uniqueArr(cell.devices.map(val => { return val.rtu_serialno }))
        let count = 0
        rtu_devices.forEach((item) => {
          actions.forEach((citem) => {
            sendCommand(citem, item).then((res) => {
              count++
              if (count === actions.length) {
                this.$message.success(res.msg)
              }
            })
          })
        })
      })
    },
    getPwmInfos(serialno) {
      const value = this.devicesObj[serialno].states.PWM
      if (!value) {
        return ''
      } else {
        return getPwmInfo(value)
      }
    },
    getDeviceImage(currentDevice) {
      return getDeviceImage(this.devicesObj[currentDevice.spray_serialno])
    },
    getValveClass(serialno) {
      return getDeviceStatus(this.devicesObj[serialno]) === 'd_run' ? 'success' : 'info'
    },
    selectAll(cell) {
      this.childSelected = uniqueArr(this.childSelected.concat(cell.devices))
    },
    cancelAll(cell) {
      this.childSelected = this.childSelected.filter(val => {
        return !cell.devices.includes(val)
      })
    },
    getSelectedValves(item) {
      return item.devices.filter((val) => {
        return this.childSelected.includes(val)
      }).length
    }
  }
}
</script>

<style lang="scss" scoped>
.collapse-title{
  width:100%;
  align-items:center;
  b{
    min-width:48px;
  }
}
</style>
